﻿using System;
using System.Collections;
using System.Collections.Generic;
using CommServer.Common;
using CommServer.Network;
using CommServer.Tasks.Common;
using System.Collections.Concurrent;

namespace CommServer.Tasks
{
    public class Task_SessionCheck : ATimingTask
    {
        private int _checkInterval = 5*60;
        public Task_SessionCheck(DateTime FirstExcuteTime, int Interval, IntervalUnit Unit)
        {
            this.FirstExcuteTime = FirstExcuteTime;
            this.Interval = Interval;
            this.Unit = Unit;
        }
        public override void Excute()
        {
            DeviceServer deviceServer = Program.GetDeviceServer();
            if (deviceServer == null)
            {
                return;
            }

            List<TcpSession> Sessions = deviceServer.GetSessions();
            ConcurrentQueue<TcpSession> pool = deviceServer.TcpServer.SessionPool;
            lock ((Sessions as ICollection).SyncRoot)
            {
                for (int i = Sessions.Count - 1; i >= 0; i--)
                {
                    TcpSession Session = Sessions[i];
                    int Seconds = (int)(DateTime.Now - Session.LastRecvProtocolFrameTime).TotalSeconds;
                    //已登录情况，不处理
                    //if (Session.TagString != null && Session.TagString != "")
                    //{
                    //    continue;
                    //}
                    //未登录情况，1分钟内未解析出协议帧，则断开连接
                    //else
                    //{
                        //刚连上来,时间还没设置
                        //if (Session.LastRecvProtocolFrameTime.ToString("yyyy") == "1970")
                        //{
                        //    continue;
                       // }
                        if (Seconds >= _checkInterval)
                        {
                            Log.Warn(Session.SessionId + " no recv protocol frame in "+ _checkInterval  + " seconds, session will be closed ");
                            Sessions.Remove(Session);
                            Session.Close(pool);
                        }
                   // }
                }
            }
        }
    }
}
